<?php

namespace App\Models;

use App\Models\Article;
use App\Models\Course;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;

class VisitUser extends Model
{
    protected $table = "c_visit_users";

    public function doctor()
    {
        return $this->hasOne('App\Models\Doctor' ,'id','doctor_id');
    }

    public function article()
    {
        return $this->hasOne('App\Models\Article', 'id', 'patient_id');
    }

    public function course()
    {
        return $this->hasOne('App\Models\Course', 'id', 'patient_id');
    }

    /**
     * @param $filter
     * @return array
     * 获取首页红点
     */
    public function getRedPoint($filter)
    {
        $num = self::where([['user_id', '=', $filter['user_id']], ['is_read', '=', 1]])->count();
        $data = [];
        if ($num > 0) {
            $data['num'] = $num;
        } else {
            $data['num'] = 0;
        }
        return $data;
    }
    
    

    /**
     * @param $param
     * 随访记录
     */
    public function List($param)
    {
        $where = [];
        if(isset($param['type'])){
            $where[] = ['type','=',$param['type']];
        }
        $data = self::where([['user_id', '=', $param['user_id']]])->where($where)->with(['doctor'])->orderByDesc("id")->orderByDesc("is_read")->simplePaginate(30);
        if (!empty($data)) {
            $list = $data->toArray();
            $url = Url::getHttpHost();
            $pro = new Professional();
            $arts = [];
            $docids = [];
            $cous = [];
            $cous_docid = [];
            $data_list = [];
            foreach ($list['data'] as $k => &$v) {
                $v['created_at'] = date("m-d",strtotime($v['created_at']));
                //添加医生信息
                if (!empty($v['doctor'])) {
                    if (!empty($v['doctor']['profile'])) {
                        $v['doctor']['profile'] = $url . 'upload/' . $v['doctor']['profile'];
                    }
                    $v['doctor']['professional_info'] = $pro->where([['id', '=', $v['doctor']['professional_id']]])->value("name");
                }
                if ($v['type'] == 1) { //群发
                    $imgs = json_decode($v['images'], true);
                    $v['images'] = (new Tool)->addHostToImage($imgs);
                } elseif ($v['type'] == 2) { //患教内容
                    if ($v['patient_type'] == 1) {
                        if (isset($arts[$v['doctor_id']]) && count($arts[$v['doctor_id']]) > 0 && in_array($v['doctor_id'], $docids)) {
                            unset($list['data'][$k]);
                            continue;
                        }
                        $article = (new Article())->where([['id', '=', $v['patient_id']]])->first();
                        if ($article) {
//                            $article->art_img = Url::getHttpHost() . 'upload/' . $article->art_img;
//                            $v['article'] = $article->toArray();
                            $arts[$v['doctor_id']][] = $article;
                            $docids[] = $v['doctor_id'];
                            //查询该医生下该用户还有没有未读文章
                            $numb = self::where([['user_id','=',$param['user_id']],['doctor_id','=',$v['doctor_id']],['type','=',2],['patient_type','=',1],['is_read','=',1]])->count();
                            if($numb >0){
                                $v['is_read'] = 1;
                            }
                        } else {
                            $v['article'] = null;
                        }
                    }else {
                        if (isset($cous[$v['doctor_id']]) && count($cous[$v['doctor_id']]) > 0 && in_array($v['doctor_id'], $cous_docid)) {
                            unset($list['data'][$k]);
                            continue;
                        }
                        $course = (new Course())->where([['id', '=', $v['patient_id']]])->first();
                        if ($course) {
//                            $article->course_img = Url::getHttpHost() . 'upload/' . $article->course_img;
//                            $v['course'] = $article->toArray();
                            $cous[$v['doctor_id']][] = $course;
                            $cous_docid[] = $v['doctor_id'];
                            //查询该医生下该用户还有没有未读文章
                            $numb = self::where([['user_id','=',$param['user_id']],['doctor_id','=',$v['doctor_id']],['type','=',2],['patient_type','=',2],['is_read','=',1]])->count();
                            if($numb >0){
                                $v['is_read'] = 1;
                            }
                        } else {
                            $v['course'] = null;
                        }
                    }
                } elseif ($v['type'] == 3) {  //自动发送

                } elseif ($v['type'] == 4) { //问卷

                }
                $data_list[] = $v;
            }
            $list['data'] = $data_list;
            return $list;
        }
        return [];
    }

    /***
     * @param $param
     * @return mixed
     * 随访详情
     */
    public function Detail($param)
    {
        $detail = self::where([['id', '=', $param['id']]])->first()->toArray();
        if ($detail['type'] == 1) { //群发
            $imgs = json_decode($detail['images'], true);
            $detail['images'] = (new Tool)->addHostToImage($imgs);
        } elseif ($detail['type'] == 2) {
            if ($detail['patient_type'] == 1) {
                $article = (new Article())->where([['id', '=', $detail['patient_id']]])->first();
                if ($article) {
                    $article->art_img = Url::getHttpHost() . 'upload/' . $article->art_img;
                    $detail['article'] = $article->toArray();
                } else {
                    $detail['article'] = [];
                }
            } else {
                $article = (new Course())->where([['id', '=', $detail['patient_id']]])->first();
                if ($article) {
                    $article->course_img = Url::getHttpHost() . 'upload/' . $article->course_img;
                    $detail['course'] = $article->toArray();
                } else {
                    $detail['course'] = [];
                }
            }
        } elseif ($detail['type'] == 3) {

        } elseif ($detail['type'] == 4) {

        }
        self::where([['id', '=', $param['id']]])->update(['is_read' => 0]);
        return $detail;
    }

    /***
     * @param $param
     * @return mixed
     * 获取随访文章列表
     */
    public function getVisitArticleList($param)
    {
        $list = self::where([['doctor_id', '=', $param['doctor_id']], ['user_id', '=', $param['user_id']], ['type', '=', 2],['patient_type','=',1]])
            ->with(['article'])
            ->orderByDesc("id")
            ->simplePaginate(30);
        if (!empty($list)) {
            $list = $list->toArray();
            $pro = new Professional();
            $doctor = new Doctor();
            foreach ($list['data'] as $k => &$v) {
                $v['time'] = date("Y-m-d",strtotime($v['created_at']));
                if (!empty($v['article'])) {
                    $dor = $doctor->where([['id','=',$v['article']['doctor_id']]])->first();
                    $v['article']['art_img'] = Url::getHttpHost() . 'upload/' . $v['article']['art_img'];
                    if(!empty($dor)){
                        $v['article']['pro_name'] = $pro->where([['id','=',$dor->professional_id]])->value("name");
                    }else{
                        $v['article']['pro_name'] = "";
                    }
                    $v['article']['content']  = strip_tags(str_replace("&nbsp;",'',$v['article']['content']));//strip_tags($v['article']['content']);
                }
            }
        }
        return $list;
    }

    /***
     * @param $param
     * @return mixed
     * 获取随访文章列表
     */
    public function getVisitCourseList($param)
    {
        $list = self::where([['doctor_id', '=', $param['doctor_id']], ['user_id', '=', $param['user_id']], ['type', '=', 2],['patient_type','=',2]])
            ->with(['course'])
            ->orderByDesc("id")
            ->simplePaginate(30);
        if (!empty($list)) {
            $list = $list->toArray();
            $pro = new Professional();
            $doctor = new Doctor();
            foreach ($list['data'] as $k => &$v) {
                $v['time'] = date("Y-m-d", strtotime($v['created_at']));
                if (!empty($v['course'])) {
                    $dor = $doctor->where([['id', '=', $v['course']['add_user_id']]])->first();
                    $v['course']['course_img'] = Url::getHttpHost() . 'upload/' . $v['course']['course_img'];
                    if (!empty($dor)) {
                        $v['course']['pro_name'] = $pro->where([['id', '=', $dor->professional_id]])->value("name");
                    } else {
                        $v['course']['pro_name'] = "";
                    }
//                    $v['course']['content'] = strip_tags(str_replace("&nbsp;", '', $v['course']['content']));//strip_tags($v['course']['content']);
                }
            }
        }
        return $list;
    }

    /***
     * @param $param
     * @return mixed
     * 设置已读
     */
    public function setReadOutPassBy($param)
    {
        $info = self::where([['id', '=', $param['id']]])->first();
        $ids = self::where([['type', '=', $info->type], ['patient_id', '=', $info->patient_id],
            ['patient_type', '=', $info->patient_type], ['work_id', '=', $info->work_id],
            ['user_id', '=', $info->user_id]])->pluck("id");
        $where[] = [function ($query) use ($ids) {
            return $query->whereIn('id', $ids);
        }];
        return self::where($where)->update(['is_read' => 0]);
    }

}
